import 'dart:convert';

import 'package:audioplayers/audioplayers.dart';
import 'package:get/get.dart';
import 'package:speed_random/common/common_fuc.dart';
import 'package:speed_random/global_data.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:vibration/vibration.dart';
import 'state.dart';
import 'dart:math';

class RandNumLogic extends GetxController {
  final RandNumState state = RandNumState();
  final cachekey = 'random_numbers';
  final player = AudioPlayer();
  @override
  void onInit() {
    super.onInit();
    initCache();

  }

  // 初始化缓存
  Future<void> initCache() async {
    final prefs = await SharedPreferences.getInstance();
    state.min.value = prefs.getInt(cachekey+'min') ?? 0;
    state.max.value = prefs.getInt(cachekey+'max') ?? 100;
    state.count.value = prefs.getInt(cachekey+'count') ?? 1;
    state.randomNumbersSum.value = prefs.getInt(cachekey+'randomNumbersSum') ?? 0;
    state.isRepeatable.value = prefs.getBool(cachekey+'isRepeatable') ?? false;
    // 新增初始化缓存
    state.scrollTime.value = prefs.getInt(cachekey+'scrollTime') ?? 3;
    state.isManualStop.value = prefs.getBool(cachekey+'isManualStop') ?? false;
    state.isSoundEnabled.value = prefs.getBool('isSoundEnabled') ?? true;
    state.isVibrationEnabled.value = prefs.getBool('isVibrationEnabled') ?? true;
    state.isShowSum.value = prefs.getBool(cachekey+'isShowSum') ?? false;
    state.isadd0.value = prefs.getBool(cachekey+'isadd0') ?? false;

    // 读取随机数列表
    final List<String>? stringNumbers = prefs.getStringList(cachekey+'randomNumbers');
    if (stringNumbers != null) {
      state.randomNumbers.value = stringNumbers;
    } else {
      state.randomNumbers.value = [];
    }
  }

  void setSave(int min, int max, int count, bool isRepeatable, int scrollTime, bool isManualStop, bool isSoundEnabled, bool isVibrationEnabled) {
    if (min > max) {
      int temp = min;
      min = max;
      max = temp;
    }
    if (count < 1) {
      count = 1;
    }
    if (count > 100) {
      count = 100;
    }
    if (min < 0) {
      min = 0;
    }
    if (max > 99999) {
      max = 99999;
    }
    // 限制滚动时间范围
    scrollTime = scrollTime.clamp(1, 9);
    state.min.value = min;
    state.max.value = max;
    state.count.value = count;
    state.isRepeatable.value = isRepeatable;
    state.scrollTime.value = scrollTime;
    state.isManualStop.value = isManualStop;
    state.isSoundEnabled.value = isSoundEnabled;
    state.isVibrationEnabled.value = isVibrationEnabled;
    //state.randomNumbers.value = [];
    saveToCache();
  }

  void setRepeatable(bool isRepeatable) {
    state.isRepeatable.value = isRepeatable;
  }

  // 保存到缓存
  Future<void> saveToCache() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setInt(cachekey+'min', state.min.value);
    prefs.setInt(cachekey+'max', state.max.value);
    prefs.setInt(cachekey+'count', state.count.value);
    prefs.setBool(cachekey+'isRepeatable', state.isRepeatable.value);
    // 新增保存到缓存
    prefs.setInt(cachekey+'scrollTime', state.scrollTime.value);
    prefs.setBool(cachekey+'isManualStop', state.isManualStop.value);
    prefs.setBool('isSoundEnabled', state.isSoundEnabled.value);
    prefs.setBool('isVibrationEnabled', state.isVibrationEnabled.value);
    prefs.setBool(cachekey+'isShowSum', state.isShowSum.value);
    prefs.setBool(cachekey+'isadd0', state.isadd0.value);
  }


  void payRunMp3({type="start"}) async {
    if (state.isSoundEnabled.value) {
      if (type=="start") {
        commonFuc.playMp3(path: globalData.soundPath);
      } else {
        commonFuc.playMp3(path: globalData.soundSuccessPath);
      }
    }

  }
  // 每 500 毫秒调用一次 generateRandomNumbersRun 方法，共调用 3 次
  void generateRandomNumbers() async {
    state.isRun.value = 1;
    int scrollTime = state.scrollTime.value.clamp(1, 9);
    int loopCount = scrollTime * 10;
    if (state.isManualStop.value) {
      loopCount = 10000;
    }
    payRunMp3();
    for (int i = 0; i < loopCount; i++) {
      if (state.isRun.value != 1) {
        generateRandomNumbersRun(isSaveCache: true);
        break;
      }
     // print(i);
      await Future.delayed(const Duration(milliseconds: 100));
      generateRandomNumbersRun(isSaveCache: loopCount==i+1);
      // 声音提示
    }
    state.isRun.value = 2;

    /*  if (state.isSoundEnabled.value) {
        //await player.play(UrlSource('https://example.com/my-audio.wav'));
        try {
          // 使用 AssetSource 播放本地音频
          player.play(AssetSource('mp3/y2181.mp3'));
        } catch (e) {
          print('播放音频出错: $e');
        }
      }*/

      // 震动提示
      if (state.isVibrationEnabled.value && await Vibration.hasVibrator() ?? false) {
        Vibration.vibrate(duration: 50);
      }
  }
  // 保存到缓存
  Future<void> saveToCachehistoryNumbers() async {
    payRunMp3(type: "stop");
    final prefs = await SharedPreferences.getInstance();
    final numbersAsStrings = state.randomNumbers.value.map((number) => number.toString()).toList();
    prefs.setStringList(cachekey+'randomNumbers', numbersAsStrings);
    prefs.setInt(cachekey+'randomNumbersSum', state.randomNumbersSum.value);

    // 保存历史记录
    prefs.setString(cachekey+'historyNumbers', jsonEncode(state.historyNumbers.value));

    // 立即停止播放音乐
  }

  void generateRandomNumbersStop() async {

  }
  void generateRandomNumbersRun({bool isSaveCache = false}) {
    try {
      // 参数校验
      if (state.min.value > state.max.value) {
        state.min.value=1;
      }
      if (state.count.value <= 0) {
        state.count.value=1;
      }

      final random = Random();
      final List<String> numbers = [];
      final int min = state.min.value;
      final int max = state.max.value;
      var count = state.count.value;
      final bool isRepeatable = state.isRepeatable.value;

      // 预生成所有可能的数字字符串
      final maxLength = max.toString().length;
      final numbersdefs = List<String>.generate(
        max - min + 1,
            (i) =>(state.isadd0.value?commonFuc.add0(min + i, len: maxLength):(min + i).toString()),
      );

      // 生成随机数逻辑
      if (isRepeatable) {
        // 可重复模式
        numbers.addAll(
          List.generate(
            count,
                (_) => numbersdefs[random.nextInt(numbersdefs.length)],
          ),
        );
      } else {
        // 不可重复模式
        if (count > numbersdefs.length) {
          count = numbersdefs.length;
        }

        final shuffled = List<String>.from(numbersdefs)..shuffle(random);
        numbers.addAll(shuffled.take(count));
      }

      // 更新状态
      state.randomNumbers.value = numbers;
      state.randomNumbersSum.value = numbers.isNotEmpty
          ? commonFuc.sumNumbers(numbers)
          : 0;

      // 缓存处理
      if (isSaveCache) {
        if (state.historyNumbers.length>=200) {
          state.historyNumbers.removeAt(0);
        }
        state.historyNumbers.add({
          "list": numbers.join(','),
          "sum": state.randomNumbersSum.value,
          "isshowsum": state.isShowSum.value,
          "time": commonFuc.getNowTimeYmdHis()
        });
        saveToCachehistoryNumbers();
      }

      update();
    } catch (e) {
      // 错误处理
     // debugPrint('生成随机数出错: $e');
      // 可以根据需要在这里添加错误恢复或状态重置逻辑
      rethrow; // 或者处理错误后继续
    }
  }
}
